﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace TaskCancel
{
    class Program
    {
        static void main()
        {
            //需要执行的任务函数
            Action taskFunction = delegate()
            {
                for (int i = 0; i < 100; i++)
                {
                    if (Task.Current.IsCancellationRequested)
                    {
                        Console.WriteLine("Task对象：响应外界请求，取消工作任务");
                        //设置Task的状态为IsCanceled
                        Task.Current.AcknowledgeCancellation();
                        break;
                    }
                    Console.WriteLine(i);
                    Thread.Sleep(200);
                    
                }
            };

            Console.WriteLine("敲任意键发出取消任务请求...");
            Task tsk = new Task(taskFunction);
           
               
                tsk.Start();
                Console.ReadKey(true);
                //发出异步取消任务请求
                    tsk.Cancel();
                    Console.WriteLine("主线程已发出取消请求！");

                    //同步等待工作任务停止  
                    tsk.CancelAndWait();
                    Console.WriteLine("主线程：任务已经取消！");
                       
            Console.ReadKey();
        }
    }
}
